package cn.iocoder.yudao.module.engine.service.core.messagestore.impl;

import cn.iocoder.yudao.module.engine.model.context.AIMessageContext;
import cn.iocoder.yudao.module.engine.model.context.ControlEngineContext;
import cn.iocoder.yudao.module.engine.model.context.EngineSessionContext;
import cn.iocoder.yudao.module.engine.model.engine.EngineOutputData;
import cn.iocoder.yudao.module.engine.service.core.messagestore.AbstractMessageStore;
import cn.iocoder.yudao.module.engine.service.core.messagestore.MessageStoreManager;
import cn.iocoder.yudao.module.resource.api.IMessageApi;
import cn.iocoder.yudao.module.resource.api.enums.MessageContentTypeEnum;
import cn.iocoder.yudao.module.resource.api.model.message.AudioDataDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;

import javax.annotation.Nullable;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import java.util.List;

@Slf4j
@Order(102)
@Service("messageStore-mysql")
public class MysqlMessageStore extends AbstractMessageStore {
    @Resource
    private IMessageApi messageApi;
    @Resource
    private MessageStoreManager messageStoreManager;

    @PostConstruct
    public void init() {
        messageStoreManager.registerStore("messageStore-mysql", this);
    }

    @Override
    public void executeSaveMessages(ControlEngineContext engineContext,
                                    @Nullable AIMessageContext messageCtx,
                                    EngineOutputData.Audio audio) {
        final EngineSessionContext sessionContext = engineContext.getSessionCtx();
        final String replyText = getReplyText(messageCtx, audio);
        final List<AudioDataDTO> audioDataList = getAudioDataList(messageCtx, audio);
        final Integer responseTimeMs = messageCtx != null ? messageCtx.getRequestLLMTimeMs() : 0;
        messageApi.createMessage(
                audio.getChatId(),
                sessionContext.getUserId(),
                audio.getMessageSendType(),
                MessageContentTypeEnum.TEXT_OR_AUDIO,
                sessionContext.getGameMatchId(),
                sessionContext.getWsSessionId(),
                sessionContext.getRoleId(),
                audio.getFromMessage(),
                replyText,
                audioDataList,
                responseTimeMs
        );
    }
}
